const EventEmitter = require('events').EventEmitter

const sanitizeDir = require('../shared/sanitizeDir')
const setProgress = require('../shared/setProgress')
const logger = require('../shared/logger')
const fetchCommand = require('../shared/fetchCommand')
const parselogstat = require('../shared/parselogstat')
const getCommitFileDiff = require('../advanced/getCommitFileDiff')
const GitData = require('../classes/GitData')
const parseBranch = require('../shared/parseBranch')
const parseCommitChunks = require('../shared/parseCommitChunks')

class Git2Stats extends EventEmitter {
  constructor(dir, options){
    super()
    this.dir = dir
    this.options = Object.assign({ silent: true, maxFileChanges:10000 },options)
    console.log(this.options)
  }

  async start() {
    let { dir, options } = this
    options.dir = sanitizeDir(dir, options)
    options = setProgress(options)
    options = logger(options)
    let command = 'git log --stat --numstat'
    if(options.after) {
      command += ` --after=${options.after}`
    }

    if(options.before) {
      command += ` --before=${options.before}`
    }
    
    // 一个chunk不一定是一个完整的commit或者多个完整的commit
    // 碰到下一个提交时才Push上一个提交或上多个提交。
    let lastCommits = ''
    const data = await fetchCommand(command, options, (chunk) => {
      // console.log(chunk.startsWith('\ncommit'))
      lastCommits += chunk
      if(chunk.startsWith('\ncommit')){
        const res = parseCommitChunks(lastCommits)
        lastCommits = ''
        return res
      }

      return null
    })
      .then(async data => {
        data = await data.map(chunk => parselogstat(chunk, options))
        for (let ci = 0; ci < data.length; ci++) {
          const commit = data[ci]
          // const diffs = await getCommitDiffs(commit.sha, options)
          // data[ci] = zipCommitDiffs(commit, diffs, options)
          if(options.hasDiff) {
            for (let fi = 0; fi < commit.files.length; fi++) {
              const file = commit.files[fi]
              data[ci].files[fi] = await getCommitFileDiff(
                commit.sha,
                file,
                options
              )
            }
          }
          this.emit('get-commit', commit)
        }
        return data
        // return logs2diff(data.map(chunk => parselogstat(chunk, options)), options)
      })
      .catch(err => { console.log(err) })
    options.logger('git2stats -> ' + data.length + ' commits')
    return new GitData(data)
  }

  async getBranch() {
    let { dir, options } = this
    options.dir = sanitizeDir(dir, options)
    options = setProgress(options)
    options = logger(options)
    let data = await fetchCommand('git branch', options)
    if(data[0]){
      data = parseBranch(data[0])
    }
    return data
  }
}

module.exports = Git2Stats